package com.sikaryofficial.qrcode.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.anwen.mongo.aggregate.pipeline.Accumulators;
import com.anwen.mongo.conditions.query.QueryWrapper;
import com.anwen.mongo.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.qrcode.config.ProductQrUrlConfig;
import com.sikaryofficial.qrcode.domain.mapping.ProductQrCodeMapping;
import com.sikaryofficial.qrcode.domain.mongo.ProductQrMongo;
import com.sikaryofficial.qrcode.service.ProductQrMongoService;
import com.sikaryofficial.qrcode.util.ProductQrUtil;
import com.sikaryofficial.system.api.domain.ProductQr;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author JiaChaoYang
 * @project mongo-plus-demo
 * @description
 * @date 2023-07-18 22:27
 **/
@Service
@Slf4j
public class ProductQrMongoServiceImpl extends ServiceImpl<ProductQrMongo> implements ProductQrMongoService {
    @Autowired
    private ProductQrUrlConfig config;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean insertBatch(List<ProductQrMongo> insertData) {
        log.info("insertBatch start");
        long startTime = System.currentTimeMillis();
        // 分批插入
        List<List<ProductQrMongo>> partitionData = Lists.partition(insertData, config.getQrInsertBatchSize());
        for (List<ProductQrMongo> list : partitionData) {
            this.saveBatch(list);
        }
        log.info("insertBatch end cost:{}ms", System.currentTimeMillis() - startTime);
        return true;
    }

    /**
     * 判断用户是否扫码获取产品100积分
     *
     * @param param
     * @return
     */
    @Override
    public Boolean existProductQrCode(String param) {
        log.info("existProductQrCode start");
        long startTime = System.currentTimeMillis();
        if (CharSequenceUtil.isBlank(param)) {
            return false;
        }
        String[] inputParam = param.split(ProductQrUtil.PARAM_SPLIT_KEY);
        Integer yearMonth = ProductQrUtil.decodeYearMonth(inputParam[3]);
        ProductQrMongo productQr = this.lambdaQuery()
                .eq(ProductQrMongo::getParam, param)
                .eq(ProductQrMongo::getQrYearMonth, yearMonth)
                .eq(ProductQrMongo::getDeletedVersion, 0L).one();
        log.info("existProductQrCode end cost:{}ms", System.currentTimeMillis() - startTime);
        return Objects.nonNull(productQr);
    }

    /**
     * 判断用户是否扫码获取产品100积分
     *
     * @param param
     * @return
     */
    @Override
    public Boolean verifyScanCode(String param) {
        log.info("verifyScanCode start");
        long startTime = System.currentTimeMillis();
        if (CharSequenceUtil.isBlank(param)) {
            return false;
        }
        String[] inputParam = param.split(ProductQrUtil.PARAM_SPLIT_KEY);
        Integer yearMonth = ProductQrUtil.decodeYearMonth(inputParam[3]);
        ProductQrMongo productQr = this.lambdaQuery()
                .eq(ProductQrMongo::getParam, param)
                .eq(ProductQrMongo::getQrYearMonth, yearMonth)
                .eq(ProductQrMongo::getDeletedVersion, 0L).one();
        log.info("verifyScanCode end cost:{}ms", System.currentTimeMillis() - startTime);
        return Optional.ofNullable(productQr)
                .map(ProductQrMongo::getHasScanCode)
                .filter(hasScanCode -> hasScanCode.equals(1))
                .isPresent();
    }

    /**
     * 更新产品二维码数据
     *
     * @param param
     */
    @Override
    public boolean updateProductQrData(String param) {
        log.info("updateProductQrData start");
        long startTime = System.currentTimeMillis();
        if (CharSequenceUtil.isBlank(param)) {
            return false;
        }
        ProductQr productQr = getProductQr(param);
        if (Objects.isNull(productQr)) {
            throw new ServiceException("productQr is empty,param:" + param);
        }
        String[] inputParam = param.split(ProductQrUtil.PARAM_SPLIT_KEY);
        Integer yearMonth = ProductQrUtil.decodeYearMonth(inputParam[3]);
        // 更新扫码记录
        return this.lambdaUpdate()
                .set(ProductQrMongo::getHasScanCode, 1)
                .set(ProductQrMongo::getUpdatedBy, 0L)
                .set(ProductQrMongo::getUpdatedTime, new Date())
                .eq(ProductQrMongo::getDeletedVersion, 0L)
                .eq(ProductQrMongo::getParam, param)
                .eq(ProductQrMongo::getQrYearMonth, yearMonth)
                .update();
    }

    /**
     * 根据参数查询二维码数据
     *
     * @param param
     * @return
     */
    @Override
    public ProductQr getProductQr(String param) {
        log.info("getProductQr start");
        long startTime = System.currentTimeMillis();
        if (CharSequenceUtil.isBlank(param)) {
            return null;
        }
        String[] inputParam = param.split(ProductQrUtil.PARAM_SPLIT_KEY);
        Integer yearMonth = ProductQrUtil.decodeYearMonth(inputParam[3]);
        ProductQrMongo productQrMongo = this.lambdaQuery()
                .eq(ProductQrMongo::getParam, param)
                .eq(ProductQrMongo::getQrYearMonth, yearMonth)
                .eq(ProductQrMongo::getDeletedVersion, 0L).one();
        if (Objects.isNull(productQrMongo)) {
            return null;
        }
        log.info("getProductQr end cost:{}ms", System.currentTimeMillis() - startTime);

        List<ProductQrMongo> productQrMongoList = this.lambdaQuery()
                .eq(ProductQrMongo::getParam, param)
                .eq(ProductQrMongo::getQrYearMonth, yearMonth)
                .eq(ProductQrMongo::getDeletedVersion, 0L).list();
        log.info("productQrMongo size:{}", productQrMongoList.size());
        return ProductQrCodeMapping.INSTANCE.coverEntity(productQrMongo);
    }

    /**
     * 查询当前产品对应的所有扫码次数
     *
     * @param brandTasteId
     * @return
     */
    @Override
    public long countScanCodeNumById(Long brandTasteId) {
        List<ProductQrMongo> results = this.lambdaAggregates().match(new QueryWrapper<ProductQrMongo>()
                .eq(ProductQrMongo::getBrandTasteId, brandTasteId)
                .gt(ProductQrMongo::getScanCodeNum, 0L)
                .eq(ProductQrMongo::getDeletedVersion, 0L)
        ).group("$brandTasteId", Accumulators.sum(ProductQrMongo::getScanCodeNum, "$scanCodeNum")).list();
        if (CollUtil.isEmpty(results)) {
            return 0L;
        }
        return results.iterator().next().getScanCodeNum();
    }

    @Override
    public long countDocument() {
        try {
            Document command = new Document("collStats", "product_qr_t");
            Document result = mongoTemplate.executeCommand(command);
            Integer count = result.getInteger("count");
            return count != null ? count.longValue() : 0L;
        } catch (Exception e) {
            log.error("countDocument error:{}", e);
            // 根据实际需求处理异常或记录日志
            return 0L;
        }
    }
}
